
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CsvOutputTool {
    /**
     * 写入csv文件
     * @param headers  列头
     * @param data     数据内容
     * @param filePath 创建的csv文件路径
     **/
    public static void writeCsv(Object[] headers, List<Object[]> data, String filePath) throws IOException {
        //初始化csvformat
        CSVFormat formator = CSVFormat.DEFAULT.withRecordSeparator("\n");
        //创建FileWriter对象
        FileWriter fileWriter = new FileWriter(filePath, true);
        //创建CSVPrinter对象
        CSVPrinter printer = new CSVPrinter(fileWriter, formator);
        //写入列头数据
        printer.printRecord(headers);
        if (null != data) {
            //循环写入数据
            for (Object[] lineData : data) {
                printer.printRecord(lineData);
            }
        }
        fileWriter.flush();
        printer.close(true);
        fileWriter.close();
    }

/*    public static void main(String[] args) throws IOException {
        Object shuzu[]={"id","code","name","中文"};
        Object shuzu1[]={"1","2","3","4"};
        Object shuzu2[]={"4","5","6","7"};
        Object shuzu3[]={4,5,6};
        ArrayList arrayList = new ArrayList();
        arrayList.add(shuzu1);
        arrayList.add(shuzu2);
        System.out.println(arrayList.get(0));
        String lujing="D:\\123.csv";
        writeCsv(shuzu,arrayList,lujing);
    }*/
}